home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / source / python / pythonrun.c < prev    next >
C/C++ Source or Header  |  1999-06-14  |  26KB  |  1,171 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Python interpreter top-level routines, including init/exit */
  33.  
  34. #include "Python.h"
  35.  
  36. #include "grammar.h"
  37. #include "node.h"
  38. #include "parsetok.h"
  39. #include "errcode.h"
  40. #include "compile.h"
  41. #include "eval.h"
  42. #include "marshal.h"
  43.  
  44. #ifdef HAVE_UNISTD_H
  45. #include <unistd.h>
  46. #endif
  47.  
  48. #ifdef HAVE_SIGNAL_H
  49. #include <signal.h>
  50. #endif
  51.  
  52. #ifdef MS_WIN32
  53. #undef BYTE
  54. #include "windows.h"
  55. #endif
  56.  
  57. extern char *Py_GetPath();
  58.  
  59. extern grammar _PyParser_Grammar; /* From graminit.c */
  60.  
  61. /* Forward */
  62. #include "protos/pythonrun.h"
  63. static void initmain Py_PROTO((void));
  64. static void initsite Py_PROTO((void));
  65. static PyObject *run_err_node Py_PROTO((node *n, char *filename,
  66.                    PyObject *globals, PyObject *locals));
  67. static PyObject *run_node Py_PROTO((node *n, char *filename,
  68.                    PyObject *globals, PyObject *locals));
  69. static PyObject *run_pyc_file Py_PROTO((FILE *fp, char *filename,
  70.                    PyObject *globals, PyObject *locals));
  71. static void err_input Py_PROTO((perrdetail *));
  72. static void initsigs Py_PROTO((void));
  73. static void call_sys_exitfunc Py_PROTO((void));
  74. static void call_ll_exitfuncs Py_PROTO((void));
  75.  
  76. int Py_DebugFlag; /* Needed by parser.c */
  77. int Py_VerboseFlag; /* Needed by import.c */
  78. int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
  79. int Py_NoSiteFlag; /* Suppress 'import site' */
  80. int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c */
  81. int Py_FrozenFlag; /* Needed by getpath.c */
  82.  
  83. static int initialized = 0;
  84.  
  85. /* API to access the initialized flag -- useful for eroteric use */
  86.  
  87. int
  88. Py_IsInitialized()
  89. {
  90.     return initialized;
  91. }
  92.  
  93. /* Global initializations.  Can be undone by Py_Finalize().  Don't
  94.    call this twice without an intervening Py_Finalize() call.  When
  95.    initializations fail, a fatal error is issued and the function does
  96.    not return.  On return, the first thread and interpreter state have
  97.    been created.
  98.  
  99.    Locking: you must hold the interpreter lock while calling this.
  100.    (If the lock has not yet been initialized, that's equivalent to
  101.    having the lock, but you cannot use multiple threads.)
  102.  
  103. */
  104.  
  105. void
  106. Py_Initialize()
  107. {
  108.     PyInterpreterState *interp;
  109.     PyThreadState *tstate;
  110.     PyObject *bimod, *sysmod;
  111.     char *p;
  112.  
  113.     if (initialized)
  114.         return;
  115.     initialized = 1;
  116.     
  117.     if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
  118.         Py_DebugFlag = 1;
  119.     if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
  120.         Py_VerboseFlag = 1;
  121.     if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
  122.         Py_OptimizeFlag = 1;
  123.  
  124.     interp = PyInterpreterState_New();
  125.     if (interp == NULL)
  126.         Py_FatalError("Py_Initialize: can't make first interpreter");
  127.  
  128.     tstate = PyThreadState_New(interp);
  129.     if (tstate == NULL)
  130.         Py_FatalError("Py_Initialize: can't make first thread");
  131.     (void) PyThreadState_Swap(tstate);
  132.  
  133.     interp->modules = PyDict_New();
  134.     if (interp->modules == NULL)
  135.         Py_FatalError("Py_Initialize: can't make modules dictionary");
  136.  
  137.     bimod = _PyBuiltin_Init_1();
  138.     if (bimod == NULL)
  139.         Py_FatalError("Py_Initialize: can't initialize __builtin__");
  140.     interp->builtins = PyModule_GetDict(bimod);
  141.     Py_INCREF(interp->builtins);
  142.  
  143.     sysmod = _PySys_Init();
  144.     if (sysmod == NULL)
  145.         Py_FatalError("Py_Initialize: can't initialize sys");
  146.     interp->sysdict = PyModule_GetDict(sysmod);
  147.     Py_INCREF(interp->sysdict);
  148.     _PyImport_FixupExtension("sys", "sys");
  149.     PySys_SetPath(Py_GetPath());
  150.     PyDict_SetItemString(interp->sysdict, "modules",
  151.                  interp->modules);
  152.  
  153.     /* phase 2 of builtins */
  154.     _PyBuiltin_Init_2(interp->builtins);
  155.     _PyImport_FixupExtension("__builtin__", "__builtin__");
  156.  
  157.     _PyImport_Init();
  158.  
  159.     initsigs(); /* Signal handling stuff, including initintr() */
  160.  
  161.     initmain(); /* Module __main__ */
  162.     if (!Py_NoSiteFlag)
  163.         initsite(); /* Module site */
  164. }
  165.  
  166. #ifdef COUNT_ALLOCS
  167. extern void dump_counts Py_PROTO((void));
  168. #endif
  169.  
  170. /* Undo the effect of Py_Initialize().
  171.  
  172.    Beware: if multiple interpreter and/or thread states exist, these
  173.    are not wiped out; only the current thread and interpreter state
  174.    are deleted.  But since everything else is deleted, those other
  175.    interpreter and thread states should no longer be used.
  176.  
  177.    (XXX We should do better, e.g. wipe out all interpreters and
  178.    threads.)
  179.  
  180.    Locking: as above.
  181.  
  182. */
  183.  
  184. void
  185. Py_Finalize()
  186. {
  187.     PyInterpreterState *interp;
  188.     PyThreadState *tstate;
  189.  
  190.     if (!initialized)
  191.         return;
  192.     initialized = 0;
  193.  
  194.     call_sys_exitfunc();
  195.  
  196.     /* Get current thread state and interpreter pointer */
  197.     tstate = PyThreadState_Get();
  198.     interp = tstate->interp;
  199.  
  200.     /* Disable signal handling */
  201.     PyOS_FiniInterrupts();
  202.  
  203.     /* Destroy PyExc_MemoryErrorInst */
  204.     _PyBuiltin_Fini_1();
  205.  
  206.     /* Destroy all modules */
  207.     PyImport_Cleanup();
  208.  
  209.     /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  210.     _PyImport_Fini();
  211.  
  212.     /* Debugging stuff */
  213. #ifdef COUNT_ALLOCS
  214.     dump_counts();
  215. #endif
  216.  
  217. #ifdef Py_REF_DEBUG
  218.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  219. #endif
  220.  
  221. #ifdef Py_TRACE_REFS
  222.     if (_Py_AskYesNo("Print left references?")) {
  223.         _Py_PrintReferences(stderr);
  224.     }
  225. #endif /* Py_TRACE_REFS */
  226.  
  227.     /* Delete current thread */
  228.     PyInterpreterState_Clear(interp);
  229.     PyThreadState_Swap(NULL);
  230.     PyInterpreterState_Delete(interp);
  231.  
  232.     /* Now we decref the exception classes.  After this point nothing
  233.        can raise an exception.  That's okay, because each Fini() method
  234.        below has been checked to make sure no exceptions are ever
  235.        raised.
  236.     */
  237.     _PyBuiltin_Fini_2();
  238.     PyMethod_Fini();
  239.     PyFrame_Fini();
  240.     PyCFunction_Fini();
  241.     PyTuple_Fini();
  242.     PyString_Fini();
  243.     PyInt_Fini();
  244.     PyFloat_Fini();
  245.  
  246.     /* XXX Still allocated:
  247.        - various static ad-hoc pointers to interned strings
  248.        - int and float free list blocks
  249.        - whatever various modules and libraries allocate
  250.     */
  251.  
  252.     PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  253.  
  254.     call_ll_exitfuncs();
  255.  
  256. #ifdef Py_TRACE_REFS
  257.     _Py_ResetReferences();
  258. #endif /* Py_TRACE_REFS */
  259. }
  260.  
  261. /* Create and initialize a new interpreter and thread, and return the
  262.    new thread.  This requires that Py_Initialize() has been called
  263.    first.
  264.  
  265.    Unsuccessful initialization yields a NULL pointer.  Note that *no*
  266.    exception information is available even in this case -- the
  267.    exception information is held in the thread, and there is no
  268.    thread.
  269.  
  270.    Locking: as above.
  271.  
  272. */
  273.  
  274. PyThreadState *
  275. Py_NewInterpreter()
  276. {
  277.     PyInterpreterState *interp;
  278.     PyThreadState *tstate, *save_tstate;
  279.     PyObject *bimod, *sysmod;
  280.  
  281.     if (!initialized)
  282.         Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  283.  
  284.     interp = PyInterpreterState_New();
  285.     if (interp == NULL)
  286.         return NULL;
  287.  
  288.     tstate = PyThreadState_New(interp);
  289.     if (tstate == NULL) {
  290.         PyInterpreterState_Delete(interp);
  291.         return NULL;
  292.     }
  293.  
  294.     save_tstate = PyThreadState_Swap(tstate);
  295.  
  296.     /* XXX The following is lax in error checking */
  297.  
  298.     interp->modules = PyDict_New();
  299.  
  300.     bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
  301.     if (bimod != NULL) {
  302.         interp->builtins = PyModule_GetDict(bimod);
  303.         Py_INCREF(interp->builtins);
  304.     }
  305.     sysmod = _PyImport_FindExtension("sys", "sys");
  306.     if (bimod != NULL && sysmod != NULL) {
  307.         interp->sysdict = PyModule_GetDict(sysmod);
  308.         Py_INCREF(interp->sysdict);
  309.         PySys_SetPath(Py_GetPath());
  310.         PyDict_SetItemString(interp->sysdict, "modules",
  311.                      interp->modules);
  312.         initmain();
  313.         if (!Py_NoSiteFlag)
  314.             initsite();
  315.     }
  316.  
  317.     if (!PyErr_Occurred())
  318.         return tstate;
  319.  
  320.     /* Oops, it didn't work.  Undo it all. */
  321.  
  322.     PyErr_Print();
  323.     PyThreadState_Clear(tstate);
  324.     PyThreadState_Swap(save_tstate);
  325.     PyThreadState_Delete(tstate);
  326.     PyInterpreterState_Delete(interp);
  327.  
  328.     return NULL;
  329. }
  330.  
  331. /* Delete an interpreter and its last thread.  This requires that the
  332.    given thread state is current, that the thread has no remaining
  333.    frames, and that it is its interpreter's only remaining thread.
  334.    It is a fatal error to violate these constraints.
  335.  
  336.    (Py_Finalize() doesn't have these constraints -- it zaps
  337.    everything, regardless.)
  338.  
  339.    Locking: as above.
  340.  
  341. */
  342.  
  343. void
  344. Py_EndInterpreter(tstate)
  345.     PyThreadState *tstate;
  346. {
  347.     PyInterpreterState *interp = tstate->interp;
  348.  
  349.     if (tstate != PyThreadState_Get())
  350.         Py_FatalError("Py_EndInterpreter: thread is not current");
  351.     if (tstate->frame != NULL)
  352.         Py_FatalError("Py_EndInterpreter: thread still has a frame");
  353.     if (tstate != interp->tstate_head || tstate->next != NULL)
  354.         Py_FatalError("Py_EndInterpreter: not the last thread");
  355.  
  356.     PyImport_Cleanup();
  357.     PyInterpreterState_Clear(interp);
  358.     PyThreadState_Swap(NULL);
  359.     PyInterpreterState_Delete(interp);
  360. }
  361.  
  362. static char *progname = "python";
  363.  
  364. void
  365. Py_SetProgramName(pn)
  366.     char *pn;
  367. {
  368.     if (pn && *pn)
  369.         progname = pn;
  370. }
  371.  
  372. char *
  373. Py_GetProgramName()
  374. {
  375.     return progname;
  376. }
  377.  
  378. static char *default_home = NULL;
  379.  
  380. void
  381. Py_SetPythonHome(home)
  382.     char *home;
  383. {
  384.     default_home = home;
  385. }
  386.  
  387. char *
  388. Py_GetPythonHome()
  389. {
  390.     char *home = default_home;
  391.     if (home == NULL)
  392.         home = getenv("PYTHONHOME");
  393.     return home;
  394. }
  395.  
  396. /* Create __main__ module */
  397.  
  398. static void
  399. initmain()
  400. {
  401.     PyObject *m, *d;
  402.     m = PyImport_AddModule("__main__");
  403.     if (m == NULL)
  404.         Py_FatalError("can't create __main__ module");
  405.     d = PyModule_GetDict(m);
  406.     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  407.         PyObject *bimod = PyImport_ImportModule("__builtin__");
  408.         if (bimod == NULL ||
  409.             PyDict_SetItemString(d, "__builtins__", bimod) != 0)
  410.             Py_FatalError("can't add __builtins__ to __main__");
  411.         Py_DECREF(bimod);
  412.     }
  413. }
  414.  
  415. /* Import the site module (not into __main__ though) */
  416.  
  417. static void
  418. initsite()
  419. {
  420.     PyObject *m, *f;
  421.     m = PyImport_ImportModule("site");
  422.     if (m == NULL) {
  423.         f = PySys_GetObject("stderr");
  424.         if (Py_VerboseFlag) {
  425.             PyFile_WriteString(
  426.                 "'import site' failed; traceback:\n", f);
  427.             PyErr_Print();
  428.         }
  429.         else {
  430.             PyFile_WriteString(
  431.               "'import site' failed; use -v for traceback\n", f);
  432.             PyErr_Clear();
  433.         }
  434.     }
  435.     else {
  436.         Py_DECREF(m);
  437.     }
  438. }
  439.  
  440. /* Parse input from a file and execute it */
  441.  
  442. int
  443. PyRun_AnyFile(fp, filename)
  444.     FILE *fp;
  445.     char *filename;
  446. {
  447.     if (filename == NULL)
  448.         filename = "???";
  449.     if (Py_FdIsInteractive(fp, filename))
  450.         return PyRun_InteractiveLoop(fp, filename);
  451.     else
  452.         return PyRun_SimpleFile(fp, filename);
  453. }
  454.  
  455. int
  456. PyRun_InteractiveLoop(fp, filename)
  457.     FILE *fp;
  458.     char *filename;
  459. {
  460.     PyObject *v;
  461.     int ret;
  462.     v = PySys_GetObject("ps1");
  463.     if (v == NULL) {
  464.         PySys_SetObject("ps1", v = PyString_FromString(">>> "));
  465.         Py_XDECREF(v);
  466.     }
  467.     v = PySys_GetObject("ps2");
  468.     if (v == NULL) {
  469.         PySys_SetObject("ps2", v = PyString_FromString("... "));
  470.         Py_XDECREF(v);
  471.     }
  472.     for (;;) {
  473.         ret = PyRun_InteractiveOne(fp, filename);
  474. #ifdef Py_REF_DEBUG
  475.         fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  476. #endif
  477.         if (ret == E_EOF)
  478.             return 0;
  479.         /*
  480.         if (ret == E_NOMEM)
  481.             return -1;
  482.         */
  483.     }
  484. }
  485.  
  486. int
  487. PyRun_InteractiveOne(fp, filename)
  488.     FILE *fp;
  489.     char *filename;
  490. {
  491.     PyObject *m, *d, *v, *w;
  492.     node *n;
  493.     perrdetail err;
  494.     char *ps1 = "", *ps2 = "";
  495.     v = PySys_GetObject("ps1");
  496.     if (v != NULL) {
  497.         v = PyObject_Str(v);
  498.         if (v == NULL)
  499.             PyErr_Clear();
  500.         else if (PyString_Check(v))
  501.             ps1 = PyString_AsString(v);
  502.     }
  503.     w = PySys_GetObject("ps2");
  504.     if (w != NULL) {
  505.         w = PyObject_Str(w);
  506.         if (w == NULL)
  507.             PyErr_Clear();
  508.         else if (PyString_Check(w))
  509.             ps2 = PyString_AsString(w);
  510.     }
  511.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar,
  512.                    Py_single_input, ps1, ps2, &err);
  513.     Py_XDECREF(v);
  514.     Py_XDECREF(w);
  515.     if (n == NULL) {
  516.         if (err.error == E_EOF) {
  517.             if (err.text)
  518.                 free(err.text);
  519.             return E_EOF;
  520.         }
  521.         err_input(&err);
  522.         PyErr_Print();
  523.         return err.error;
  524.     }
  525.     m = PyImport_AddModule("__main__");
  526.     if (m == NULL)
  527.         return -1;
  528.     d = PyModule_GetDict(m);
  529.     v = run_node(n, filename, d, d);
  530.     if (v == NULL) {
  531.         PyErr_Print();
  532.         return -1;
  533.     }
  534.     Py_DECREF(v);
  535.     if (Py_FlushLine())
  536.         PyErr_Clear();
  537.     return 0;
  538. }
  539.  
  540. int
  541. PyRun_SimpleFile(fp, filename)
  542.     FILE *fp;
  543.     char *filename;
  544. {
  545.     PyObject *m, *d, *v;
  546.     char *ext;
  547.  
  548.     m = PyImport_AddModule("__main__");
  549.     if (m == NULL)
  550.         return -1;
  551.     d = PyModule_GetDict(m);
  552.     ext = filename + strlen(filename) - 4;
  553. #ifdef _AMIGA
  554.     /* on Amiga, filenames are case insensitive */
  555.     if (stricmp(ext, ".pyc") == 0 || stricmp(ext, ".pyo") == 0
  556. #else
  557.     if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
  558. #endif /* _AMIGA */
  559. #ifdef macintosh
  560.     /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
  561.         || getfiletype(filename) == 'PYC '
  562.         || getfiletype(filename) == 'APPL'
  563. #endif /* macintosh */
  564.         ) {
  565.         /* Try to run a pyc file. First, re-open in binary */
  566.         /* Don't close, done in main: fclose(fp); */
  567.         if( (fp = fopen(filename, "rb")) == NULL ) {
  568.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  569.             return -1;
  570.         }
  571.         /* Turn on optimization if a .pyo file is given */
  572.         if (strcmp(ext, ".pyo") == 0)
  573.             Py_OptimizeFlag = 1;
  574.         v = run_pyc_file(fp, filename, d, d);
  575.     } else {
  576.         v = PyRun_File(fp, filename, Py_file_input, d, d);
  577.     }
  578.     if (v == NULL) {
  579.         PyErr_Print();
  580.         return -1;
  581.     }
  582.     Py_DECREF(v);
  583.     if (Py_FlushLine())
  584.         PyErr_Clear();
  585.     return 0;
  586. }
  587.  
  588. int
  589. PyRun_SimpleString(command)
  590.     char *command;
  591. {
  592.     PyObject *m, *d, *v;
  593.     m = PyImport_AddModule("__main__");
  594.     if (m == NULL)
  595.         return -1;
  596.     d = PyModule_GetDict(m);
  597.     v = PyRun_String(command, Py_file_input, d, d);
  598.     if (v == NULL) {
  599.         PyErr_Print();
  600.         return -1;
  601.     }
  602.     Py_DECREF(v);
  603.     if (Py_FlushLine())
  604.         PyErr_Clear();
  605.     return 0;
  606. }
  607.  
  608. static int
  609. parse_syntax_error(err, message, filename, lineno, offset, text)
  610.      PyObject* err;
  611.      PyObject** message;
  612.      char** filename;
  613.      int* lineno;
  614.      int* offset;
  615.      char** text;
  616. {
  617.     long hold;
  618.     PyObject *v;
  619.  
  620.     /* old style errors */
  621.     if (PyTuple_Check(err))
  622.         return PyArg_Parse(err, "(O(ziiz))", message, filename,
  623.                    lineno, offset, text);
  624.  
  625.     /* new style errors.  `err' is an instance */
  626.  
  627.     if (! (v = PyObject_GetAttrString(err, "msg")))
  628.         goto finally;
  629.     *message = v;
  630.  
  631.     if (!(v = PyObject_GetAttrString(err, "filename")))
  632.         goto finally;
  633.     if (v == Py_None)
  634.         *filename = NULL;
  635.     else if (! (*filename = PyString_AsString(v)))
  636.         goto finally;
  637.  
  638.     Py_DECREF(v);
  639.     if (!(v = PyObject_GetAttrString(err, "lineno")))
  640.         goto finally;
  641.     hold = PyInt_AsLong(v);
  642.     Py_DECREF(v);
  643.     v = NULL;
  644.     if (hold < 0 && PyErr_Occurred())
  645.         goto finally;
  646.     *lineno = (int)hold;
  647.  
  648.     if (!(v = PyObject_GetAttrString(err, "offset")))
  649.         goto finally;
  650.     hold = PyInt_AsLong(v);
  651.     Py_DECREF(v);
  652.     v = NULL;
  653.     if (hold < 0 && PyErr_Occurred())
  654.         goto finally;
  655.     *offset = (int)hold;
  656.  
  657.     if (!(v = PyObject_GetAttrString(err, "text")))
  658.         goto finally;
  659.     if (v == Py_None)
  660.         *text = NULL;
  661.     else if (! (*text = PyString_AsString(v)))
  662.         goto finally;
  663.     Py_DECREF(v);
  664.     return 1;
  665.  
  666. finally:
  667.     Py_XDECREF(v);
  668.     return 0;
  669. }
  670.  
  671. void
  672. PyErr_Print()
  673. {
  674.     PyErr_PrintEx(1);
  675. }
  676.  
  677. void
  678. PyErr_PrintEx(set_sys_last_vars)
  679.     int set_sys_last_vars;
  680. {
  681.     int err = 0;
  682.     PyObject *exception, *v, *tb, *f;
  683.     PyErr_Fetch(&exception, &v, &tb);
  684.     PyErr_NormalizeException(&exception, &v, &tb);
  685.  
  686.     if (exception == NULL)
  687.         return;
  688.  
  689.     if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
  690.         if (Py_FlushLine())
  691.             PyErr_Clear();
  692.         fflush(stdout);
  693.         if (v == NULL || v == Py_None)
  694.             Py_Exit(0);
  695.         if (PyInstance_Check(v)) {
  696.             /* we expect the error code to be store in the
  697.                `code' attribute
  698.             */
  699.             PyObject *code = PyObject_GetAttrString(v, "code");
  700.             if (code) {
  701.                 Py_DECREF(v);
  702.                 v = code;
  703.                 if (v == Py_None)
  704.                     Py_Exit(0);
  705.             }
  706.             /* if we failed to dig out the "code" attribute,
  707.                then just let the else clause below print the
  708.                error
  709.             */
  710.         }
  711.         if (PyInt_Check(v))
  712.             Py_Exit((int)PyInt_AsLong(v));
  713.         else {
  714.             /* OK to use real stderr here */
  715.             PyObject_Print(v, stderr, Py_PRINT_RAW);
  716.             fprintf(stderr, "\n");
  717.             Py_Exit(1);
  718.         }
  719.     }
  720.     if (set_sys_last_vars) {
  721.         PySys_SetObject("last_type", exception);
  722.         PySys_SetObject("last_value", v);
  723.         PySys_SetObject("last_traceback", tb);
  724.     }
  725.     f = PySys_GetObject("stderr");
  726.     if (f == NULL)
  727.         fprintf(stderr, "lost sys.stderr\n");
  728.     else {
  729.         if (Py_FlushLine())
  730.             PyErr_Clear();
  731.         fflush(stdout);
  732.         err = PyTraceBack_Print(tb, f);
  733.         if (err == 0 &&
  734.             PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
  735.         {
  736.             PyObject *message;
  737.             char *filename, *text;
  738.             int lineno, offset;
  739.             if (!parse_syntax_error(v, &message, &filename,
  740.                         &lineno, &offset, &text))
  741.                 PyErr_Clear();
  742.             else {
  743.                 char buf[10];
  744.                 PyFile_WriteString("  File \"", f);
  745.                 if (filename == NULL)
  746.                     PyFile_WriteString("<string>", f);
  747.                 else
  748.                     PyFile_WriteString(filename, f);
  749.                 PyFile_WriteString("\", line ", f);
  750.                 sprintf(buf, "%d", lineno);
  751.                 PyFile_WriteString(buf, f);
  752.                 PyFile_WriteString("\n", f);
  753.                 if (text != NULL) {
  754.                     char *nl;
  755.                     if (offset > 0 &&
  756.                         offset == (int)strlen(text))
  757.                         offset--;
  758.                     for (;;) {
  759.                         nl = strchr(text, '\n');
  760.                         if (nl == NULL ||
  761.                             nl-text >= offset)
  762.                             break;
  763.                         offset -= (nl+1-text);
  764.                         text = nl+1;
  765.                     }
  766.                     while (*text == ' ' || *text == '\t') {
  767.                         text++;
  768.                         offset--;
  769.                     }
  770.                     PyFile_WriteString("    ", f);
  771.                     PyFile_WriteString(text, f);
  772.                     if (*text == '\0' ||
  773.                         text[strlen(text)-1] != '\n')
  774.                         PyFile_WriteString("\n", f);
  775.                     PyFile_WriteString("    ", f);
  776.                     offset--;
  777.                     while (offset > 0) {
  778.                         PyFile_WriteString(" ", f);
  779.                         offset--;
  780.                     }
  781.                     PyFile_WriteString("^\n", f);
  782.                 }
  783.                 Py_INCREF(message);
  784.                 Py_DECREF(v);
  785.                 v = message;
  786.                 /* Can't be bothered to check all those
  787.                    PyFile_WriteString() calls */
  788.                 if (PyErr_Occurred())
  789.                     err = -1;
  790.             }
  791.         }
  792.         if (err) {
  793.             /* Don't do anything else */
  794.         }
  795.         else if (PyClass_Check(exception)) {
  796.             PyClassObject* exc = (PyClassObject*)exception;
  797.             PyObject* className = exc->cl_name;
  798.             PyObject* moduleName =
  799.                   PyDict_GetItemString(exc->cl_dict, "__module__");
  800.  
  801.             if (moduleName == NULL)
  802.                 err = PyFile_WriteString("<unknown>", f);
  803.             else {
  804.                 char* modstr = PyString_AsString(moduleName);
  805.                 if (modstr && strcmp(modstr, "exceptions")) 
  806.                 {
  807.                     err = PyFile_WriteString(modstr, f);
  808.                     err += PyFile_WriteString(".", f);
  809.                 }
  810.             }
  811.             if (err == 0) {
  812.                 if (className == NULL)
  813.                       err = PyFile_WriteString("<unknown>", f);
  814.                 else
  815.                       err = PyFile_WriteObject(className, f,
  816.                                    Py_PRINT_RAW);
  817.             }
  818.         }
  819.         else
  820.             err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
  821.         if (err == 0) {
  822.             if (v != NULL && v != Py_None) {
  823.                 PyObject *s = PyObject_Str(v);
  824.                 /* only print colon if the str() of the
  825.                    object is not the empty string
  826.                 */
  827.                 if (s == NULL)
  828.                     err = -1;
  829.                 else if (!PyString_Check(s) ||
  830.                      PyString_GET_SIZE(s) != 0)
  831.                     err = PyFile_WriteString(": ", f);
  832.                 if (err == 0)
  833.                   err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
  834.                 Py_XDECREF(s);
  835.             }
  836.         }
  837.         if (err == 0)
  838.             err = PyFile_WriteString("\n", f);
  839.     }
  840.     Py_XDECREF(exception);
  841.     Py_XDECREF(v);
  842.     Py_XDECREF(tb);
  843.     /* If an error happened here, don't show it.
  844.        XXX This is wrong, but too many callers rely on this behavior. */
  845.     if (err != 0)
  846.         PyErr_Clear();
  847. }
  848.  
  849. PyObject *
  850. PyRun_String(str, start, globals, locals)
  851.     char *str;
  852.     int start;
  853.     PyObject *globals, *locals;
  854. {
  855.     return run_err_node(PyParser_SimpleParseString(str, start),
  856.                 "<string>", globals, locals);
  857. }
  858.  
  859. PyObject *
  860. PyRun_File(fp, filename, start, globals, locals)
  861.     FILE *fp;
  862.     char *filename;
  863.     int start;
  864.     PyObject *globals, *locals;
  865. {
  866.     return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
  867.                 filename, globals, locals);
  868. }
  869.  
  870. static PyObject *
  871. run_err_node(n, filename, globals, locals)
  872.     node *n;
  873.     char *filename;
  874.     PyObject *globals, *locals;
  875. {
  876.     if (n == NULL)
  877.         return  NULL;
  878.     return run_node(n, filename, globals, locals);
  879. }
  880.  
  881. static PyObject *
  882. run_node(n, filename, globals, locals)
  883.     node *n;
  884.     char *filename;
  885.     PyObject *globals, *locals;
  886. {
  887.     PyCodeObject *co;
  888.     PyObject *v;
  889.     co = PyNode_Compile(n, filename);
  890.     PyNode_Free(n);
  891.     if (co == NULL)
  892.         return NULL;
  893.     v = PyEval_EvalCode(co, globals, locals);
  894.     Py_DECREF(co);
  895.     return v;
  896. }
  897.  
  898. static PyObject *
  899. run_pyc_file(fp, filename, globals, locals)
  900.     FILE *fp;
  901.     char *filename;
  902.     PyObject *globals, *locals;
  903. {
  904.     PyCodeObject *co;
  905.     PyObject *v;
  906.     long magic;
  907.     long PyImport_GetMagicNumber();
  908.  
  909.     magic = PyMarshal_ReadLongFromFile(fp);
  910.     if (magic != PyImport_GetMagicNumber()) {
  911.         PyErr_SetString(PyExc_RuntimeError,
  912.                "Bad magic number in .pyc file");
  913.         return NULL;
  914.     }
  915.     (void) PyMarshal_ReadLongFromFile(fp);
  916.     v = PyMarshal_ReadObjectFromFile(fp);
  917.     fclose(fp);
  918.     if (v == NULL || !PyCode_Check(v)) {
  919.         Py_XDECREF(v);
  920.         PyErr_SetString(PyExc_RuntimeError,
  921.                "Bad code object in .pyc file");
  922.         return NULL;
  923.     }
  924.     co = (PyCodeObject *)v;
  925.     v = PyEval_EvalCode(co, globals, locals);
  926.     Py_DECREF(co);
  927.     return v;
  928. }
  929.  
  930. PyObject *
  931. Py_CompileString(str, filename, start)
  932.     char *str;
  933.     char *filename;
  934.     int start;
  935. {
  936.     node *n;
  937.     PyCodeObject *co;
  938.     n = PyParser_SimpleParseString(str, start);
  939.     if (n == NULL)
  940.         return NULL;
  941.     co = PyNode_Compile(n, filename);
  942.     PyNode_Free(n);
  943.     return (PyObject *)co;
  944. }
  945.  
  946. /* Simplified interface to parsefile -- return node or set exception */
  947.  
  948. node *
  949. PyParser_SimpleParseFile(fp, filename, start)
  950.     FILE *fp;
  951.     char *filename;
  952.     int start;
  953. {
  954.     node *n;
  955.     perrdetail err;
  956.     n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
  957.                 (char *)0, (char *)0, &err);
  958.     if (n == NULL)
  959.         err_input(&err);
  960.     return n;
  961. }
  962.  
  963. /* Simplified interface to parsestring -- return node or set exception */
  964.  
  965. node *
  966. PyParser_SimpleParseString(str, start)
  967.     char *str;
  968.     int start;
  969. {
  970.     node *n;
  971.     perrdetail err;
  972.     n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
  973.     if (n == NULL)
  974.         err_input(&err);
  975.     return n;
  976. }
  977.  
  978. /* Set the error appropriate to the given input error code (see errcode.h) */
  979.  
  980. static void
  981. err_input(err)
  982.     perrdetail *err;
  983. {
  984.     PyObject *v, *w;
  985.     char *msg = NULL;
  986.     v = Py_BuildValue("(ziiz)", err->filename,
  987.                 err->lineno, err->offset, err->text);
  988.     if (err->text != NULL) {
  989.         free(err->text);
  990.         err->text = NULL;
  991.     }
  992.     switch (err->error) {
  993.     case E_SYNTAX:
  994.         msg = "invalid syntax";
  995.         break;
  996.     case E_TOKEN:
  997.         msg = "invalid token";
  998.         break;
  999.     case E_INTR:
  1000.         PyErr_SetNone(PyExc_KeyboardInterrupt);
  1001.         Py_XDECREF(v);
  1002.         return;
  1003.     case E_NOMEM:
  1004.         PyErr_NoMemory();
  1005.         Py_XDECREF(v);
  1006.         return;
  1007.     case E_EOF:
  1008.         msg = "unexpected EOF while parsing";
  1009.         break;
  1010.     case E_INDENT:
  1011.         msg = "inconsistent use of tabs and spaces in indentation";
  1012.         break;
  1013.     default:
  1014.         fprintf(stderr, "error=%d\n", err->error);
  1015.         msg = "unknown parsing error";
  1016.         break;
  1017.     }
  1018.     w = Py_BuildValue("(sO)", msg, v);
  1019.     Py_XDECREF(v);
  1020.     PyErr_SetObject(PyExc_SyntaxError, w);
  1021.     Py_XDECREF(w);
  1022. }
  1023.  
  1024. /* Print fatal error message and abort */
  1025.  
  1026. void
  1027. Py_FatalError(msg)
  1028.     char *msg;
  1029. {
  1030.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  1031. #ifdef macintosh
  1032.     for (;;);
  1033. #endif
  1034. #ifdef MS_WIN32
  1035.     OutputDebugString("Fatal Python error: ");
  1036.     OutputDebugString(msg);
  1037.     OutputDebugString("\n");
  1038. #ifdef _DEBUG
  1039.     DebugBreak();
  1040. #endif
  1041. #endif /* MS_WIN32 */
  1042.     abort();
  1043. }
  1044.  
  1045. /* Clean up and exit */
  1046.  
  1047. #ifdef WITH_THREAD
  1048. #include "pythread.h"
  1049. int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
  1050. #endif
  1051.  
  1052. #define NEXITFUNCS 32
  1053. static void (*exitfuncs[NEXITFUNCS]) Py_PROTO((void));
  1054. static int nexitfuncs = 0;
  1055.  
  1056. int Py_AtExit(func)
  1057.     void (*func) Py_PROTO((void));
  1058. {
  1059.     if (nexitfuncs >= NEXITFUNCS)
  1060.         return -1;
  1061.     exitfuncs[nexitfuncs++] = func;
  1062.     return 0;
  1063. }
  1064.  
  1065. static void
  1066. call_sys_exitfunc()
  1067. {
  1068.     PyObject *exitfunc = PySys_GetObject("exitfunc");
  1069.  
  1070.     if (exitfunc) {
  1071.         PyObject *res, *f;
  1072.         Py_INCREF(exitfunc);
  1073.         PySys_SetObject("exitfunc", (PyObject *)NULL);
  1074.         f = PySys_GetObject("stderr");
  1075.         res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
  1076.         if (res == NULL) {
  1077.             if (f)
  1078.                 PyFile_WriteString("Error in sys.exitfunc:\n", f);
  1079.             PyErr_Print();
  1080.         }
  1081.         Py_DECREF(exitfunc);
  1082.     }
  1083.  
  1084.     if (Py_FlushLine())
  1085.         PyErr_Clear();
  1086. }
  1087.  
  1088. static void
  1089. call_ll_exitfuncs()
  1090. {
  1091.     while (nexitfuncs > 0)
  1092.         (*exitfuncs[--nexitfuncs])();
  1093.  
  1094.     fflush(stdout);
  1095.     fflush(stderr);
  1096. }
  1097.  
  1098. void
  1099. Py_Exit(sts)
  1100.     int sts;
  1101. {
  1102.     Py_Finalize();
  1103.  
  1104. #ifdef macintosh
  1105.     PyMac_Exit(sts);
  1106. #else
  1107.     exit(sts);
  1108. #endif
  1109. }
  1110.  
  1111. static void
  1112. initsigs()
  1113. {
  1114. #ifdef HAVE_SIGNAL_H
  1115. #ifdef SIGPIPE
  1116.     signal(SIGPIPE, SIG_IGN);
  1117. #endif
  1118. #endif /* HAVE_SIGNAL_H */
  1119.     PyOS_InitInterrupts(); /* May imply initsignal() */
  1120. }
  1121.  
  1122. #ifdef Py_TRACE_REFS
  1123. /* Ask a yes/no question */
  1124.  
  1125. int
  1126. _Py_AskYesNo(prompt)
  1127.     char *prompt;
  1128. {
  1129.     char buf[256];
  1130.     
  1131.     printf("%s [ny] ", prompt);
  1132.     if (fgets(buf, sizeof buf, stdin) == NULL)
  1133.         return 0;
  1134.     return buf[0] == 'y' || buf[0] == 'Y';
  1135. }
  1136. #endif
  1137.  
  1138. #ifdef MPW
  1139.  
  1140. /* Check for file descriptor connected to interactive device.
  1141.    Pretend that stdin is always interactive, other files never. */
  1142.  
  1143. int
  1144. isatty(fd)
  1145.     int fd;
  1146. {
  1147.     return fd == fileno(stdin);
  1148. }
  1149.  
  1150. #endif
  1151.  
  1152. /*
  1153.  * The file descriptor fd is considered ``interactive'' if either
  1154.  *   a) isatty(fd) is TRUE, or
  1155.  *   b) the -i flag was given, and the filename associated with
  1156.  *      the descriptor is NULL or "<stdin>" or "???".
  1157.  */
  1158. int
  1159. Py_FdIsInteractive(fp, filename)
  1160.     FILE *fp;
  1161.     char *filename;
  1162. {
  1163.     if (isatty((int)fileno(fp)))
  1164.         return 1;
  1165.     if (!Py_InteractiveFlag)
  1166.         return 0;
  1167.     return (filename == NULL) ||
  1168.            (strcmp(filename, "<stdin>") == 0) ||
  1169.            (strcmp(filename, "???") == 0);
  1170. }
  1171.